<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <p id="app">Hello</p>
</head>
<body>
    <div></div>
    <script>
        let data = {
            title: 'My Webpage exercises',
            dog: {
                age: 12,
                name: 'Baby'
            },
            arr: [1, 2, 3, 4, 5]
        };

        let vm = {};
        let attachVariables = (sVm, sData) => {
            Object.keys(sData).forEach(key => {
                let value = sData[key];
                Object.defineProperty(sVm, key, {
                    enumerable: true,
                    configurable: true,
                    get() {
                        console.log(`获取的值：${value}`);
                        if (value instanceof Array) { //当某一值为数组的时候
                            let returnArr = [];
                            attachVariables(returnArr, value);
                            return returnArr;
                        } else if (value instanceof Object) { //当某一值为对象的时候
                            let currentVM = {};
                            attachVariables(currentVM, value);
                            return currentVM;
                        } else return value;
                    },
                    set(newValue) {
                        console.log(`赋上的值：${newValue}`);
                        if (newValue === value){ return; }
                        else {
                            sData[key] = newValue;
                            document.querySelector('#app').innerHTML = newValue;
                        }
                    }
                })
            });
        };

        attachVariables(vm, data);
        vm.title = '你的背包';

    </script>
</body>
</html>